﻿// BEGIN - DETECT AJAX REQUEST
(function () {
    var proxied = window.XMLHttpRequest.prototype.send;
    window.XMLHttpRequest.prototype.send = function () {
        //console.log(arguments);
        //Here is where you can add any code to process the request.
        //If you want to pass the Ajax request object, pass the 'pointer' below
        var pointer = this;
        var intervalId = window.setInterval(function () {
            if (pointer.readyState != 4) {
                return;
            }
            //console.log(pointer.responseText);
            //Here is where you can add any code to process the response.
            //If you want to pass the Ajax request object, pass the 'pointer' below
            clearInterval(intervalId);

            // BEGIN - REPLACE ERROR AVATAR
            $('.user-avatar').on('error', function () {
                this.onerror = null;
                this.src = '/Content/Images/GetUserPhoto.png';
            });
            // END - REPLACE ERROR AVATAR
        }, 1);//I found a delay of 1 to be sufficient, modify it as you need.
        return proxied.apply(this, [].slice.call(arguments));
    };
})();
// END - DETECT AJAX REQUEST

$(function () {
    // BEGIN - CUSTOM BOOTSTRAP BUTTON GROUPS
    $('.btn-group .btn').on('click', function () {
        var checkbox = $(this).find('input[type="checkbox"]');
        if ($(this).hasClass('active')) {
            checkbox.removeAttr('checked');
        } else {
            checkbox.attr('checked', 'checked');
        }
        // On [Home], the change event is triggered automatically when the checkbox is unchecked,
        // but on [Feedback] it's not???
        checkbox.trigger('change');
    });
    // END - CUSTOM BOOTSTRAP BUTTON GROUPS

    // BEGIN - INITIALIZE DATETIMEPICKER
    $('.input-group.year').datetimepicker({
        format: 'YYYY',
        viewMode: 'years',
    });
    $('.input-group.year').on('dp.change', requestData);
    // END - INITIALIZE DATETIMEPICKER

    // BEGIN - DRAGGABLE PANELS
    var element = ".sortable-holder";
    var handle = ".sortable-handle";
    var connect = "[class*=col]";
    $(element)
        .sortable({
            handle: handle,
            connectWith: connect,
            tolerance: 'pointer',
            forcePlaceholderSize: true,
            opacity: 0.8
        })
        .disableSelection();
    // END - DRAGGABLE PANELS
});

// Do a searching operation with submitted data
function requestData(e) {
    $(e.target).closest('form').submit();
}

// Replace error avatar
function handleImageError(content) {
    this.onerror = null;
    this.src = content;
}